const query = require("../mysql/query"); 
const jwt=require('jsonwebtoken')


//登录接口
var Login = async (ctx, next) => {
  let name = ctx.request.body.userName || ''
  let password = ctx.request.body.password || ''
  let sql = `SELECT * FROM login WHERE user_name='${name}'`
  let query_res = await query(sql)
  let useId = query_res[0].useId
  if(query_res[0].password == password){
    //用户名密码校验通过，生成token
    let token=jwt.sign({name,password,useId,time:new Date().getTime(),timeout:1000*60*60*2},'token')
    ctx.body = {
      data:token,
      userInfo:{
        auth:query_res[0].auth,
        depart:query_res[0].depart_id,
        useId:useId
      },
      code:'200',
      msg:'成功'
    }
  }else{
    ctx.body = {
      data:'密码错误',
      code:'200',
      msg:'失败'
    }
  }
};

var Signin = async (ctx, next) => {
  var
      name = ctx.request.body.name || '',
      password = ctx.request.body.password || '';
  if (name === 'koa' && password === '12345') {
      ctx.body = {
        code:'200',
        msg:"注册成功",
        data:`<h1>Welcome, ${name}!</h1>`
      }
  } else {
    ctx.body = {
      code:'200',
      msg:"注册失败",
      data:`<h1>error, ${name}!</h1>`
    }
  }
};


module.exports = {
  'POST /login': Login,
  'POST /signin': Signin
};